package com.example.order.scheduler;

import com.example.order.dto.OrderRequest;
import com.example.order.dto.OrderResponse;
import com.example.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Random;

@Component
public class OrderProcessScheduler {
    private static final Logger logger = LoggerFactory.getLogger(OrderProcessScheduler.class);

    private final OrderService orderService;
    private final Random random = new Random();

    public OrderProcessScheduler(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 定时执行订单完整流程：创建 -> 支付 -> 取消
     * 每30秒执行一次
     */
    @Scheduled(fixedRate = 1000)
    public void executeOrderProcess() {
        logger.info("开始执行订单自动化流程");

        try {
            // 1. 创建订单
            String orderId = createOrder();
            if (orderId == null) {
                logger.error("创建订单失败，终止流程");
                return;
            }

            // 随机决定是否支付订单（80%概率）
            if (random.nextInt(100) < 80) {
                // 2. 支付订单
                if (payOrder(orderId)) {
                    // 随机决定是否取消已支付订单（30%概率）
                    if (random.nextInt(100) < 30) {
                        cancelOrder(orderId);
                    }
                }
            } else {
                // 随机决定是否取消未支付订单（70%概率）
                if (random.nextInt(100) < 70) {
                    cancelOrder(orderId);
                }
            }

            logger.info("订单自动化流程执行完成");
        } catch (Exception e) {
            logger.error("订单自动化流程执行异常", e);
        }
    }

    /**
     * 创建订单
     */
    private String createOrder() {
        try {
            // 构造随机订单请求
            String[] products = {"iPhone", "iPad", "MacBook", "AirPods", "Apple Watch"};
            String product = products[random.nextInt(products.length)];
            String userId = "user_" + random.nextInt(1000);
            double price = (random.nextDouble() * 1000) + 100;

            OrderRequest request = new OrderRequest(product, userId, BigDecimal.valueOf(price));

            // 直接调用service创建订单
            com.example.order.dto.OrderDTO order = orderService.createOrder(request);
            logger.info("自动创建订单成功: {}", order.getId());
            return order.getId();
        } catch (Exception e) {
            logger.error("自动创建订单失败", e);
            return null;
        }
    }

    /**
     * 支付订单
     */
    private boolean payOrder(String orderId) {
        try {
            orderService.payOrder(orderId, getRandomPaymentMethod());
            logger.info("自动支付订单成功: {}", orderId);
            return true;
        } catch (Exception e) {
            logger.error("自动支付订单失败: {}", orderId, e);
            return false;
        }
    }

    /**
     * 取消订单
     */
    private boolean cancelOrder(String orderId) {
        try {
            orderService.cancelOrder(orderId);
            logger.info("自动取消订单成功: {}", orderId);
            return true;
        } catch (Exception e) {
            logger.error("自动取消订单失败: {}", orderId, e);
            return false;
        }
    }

    /**
     * 获取随机支付方式
     */
    private String getRandomPaymentMethod() {
        String[] paymentMethods = {"alipay", "wechat", "credit_card", "debit_card"};
        return paymentMethods[random.nextInt(paymentMethods.length)];
    }
}

